/*
 * CThreadManager.java
 *
 * Copyright (c) 2009 Giles Millward (Manigra). All rights reserved.
 *
 * This file is part of JRogueDPS.
 *
 * JRogueDPS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * JRogueDPS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JRogueDPS.  If not, see <http://www.gnu.org/licenses/>.
 */
package dpssystem;

import dpsinterface.CDPSInterface;
import dpsstats.CAllStats;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;
import jroguedps.CGlobal;
import jroguedps.CRootJFrame;

/**
 *
 * @author gmillward
 */
public class CThreadManager {

    static double m_maxTime = 60.0 * 5;
    static int m_iterations = 200;

    public static void runSimulation(JTextField p_standardDeviation, 
                                     JTextField p_dpsText,
                                     JTextField p_savedDpsText)
    {
        CDPSInterface l_interface = new CDPSInterface();
        CAllStats l_stats;

        try {
            l_stats = dpssystem.CThreadManager.runSimulationThreads(l_interface, m_maxTime);
            double l_averageDps = l_stats.getTotalDPS();
            double l_stdDeviation = l_stats.getStandardDeviation();
            CGlobal.g_DPSResults.updateResults(l_stats, l_averageDps, l_stdDeviation);
            p_dpsText.setText("" + CUtil.trunc1(l_averageDps));
            p_standardDeviation.setText("" + CUtil.trunc1(l_stdDeviation) + " (" + CUtil.trunc2((l_stdDeviation / l_averageDps) * 100.0) + "%)");
            if (!p_savedDpsText.getText().equals("0")) {
                double l_percentDifference = ((l_averageDps / CGlobal.g_savedDps) - 1.0) * 100.0;
                p_savedDpsText.setText(CGlobal.g_savedDps + " (" + CUtil.trunc1(l_percentDifference) + "%)");
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(CRootJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static CAllStats runSimulationThreads(CDPSInterface p_interface, double p_maxTime) throws InterruptedException
    {
        long l_startTime = System.currentTimeMillis();
        ArrayList<CSim> l_threads = new ArrayList<CSim>();
        int l_iterations = m_iterations;
        int l_lastThreadJoined = -1;

        for (int i = 0; i < l_iterations; i ++)
        {
            CSim l_sim = new CSim(p_interface, p_maxTime, i);
            l_threads.add(l_sim);
        }

        Runtime l_runtime = Runtime.getRuntime();
        int l_nrOfProcessors = l_runtime.availableProcessors();
        for (int i = 0; i < l_iterations; i++)
        {
            l_threads.get(i).start();

            if ((i + 1) % l_nrOfProcessors == 0 && i != 0)
            {
                for (int j = (i + 1) - l_nrOfProcessors; j <= i; j++)
                {
                    l_threads.get(j).join();
                    l_lastThreadJoined = j;
                }
            }
        }

        for (int i = l_lastThreadJoined + 1; i < l_iterations; i++)
        {
            // join with the last of the threads if there are any
            l_threads.get(i).join();
        }

        double l_totalTime = (((double) (System.currentTimeMillis() - l_startTime)) / 1000.0);
        double l_perIteration = l_totalTime / l_iterations;

        CGlobal.g_rootFrame.iterationsLabel.setText("Iterations: " + l_iterations);
        CGlobal.g_rootFrame.fightLengthLabel.setText("Fight Length: " + p_maxTime + "s");
        CGlobal.g_rootFrame.timePerIterationLabel.setText("Time Per Iteration: " + CUtil.trunc6(l_perIteration) + "s");
        CGlobal.g_rootFrame.totalTimeLabel.setText("Total Calculation Time: " + CUtil.trunc4(l_totalTime) + "s");
        CGlobal.g_rootFrame.cpuCountLabel.setText("CPU Count: " + l_nrOfProcessors);


        // Create a single instance of the stats
        CAllStats l_allStats = new CAllStats(l_threads.get(0).m_stats);

        for (int i = 0; i < l_iterations; i++)
        {
            // Total up the stats
            l_allStats.add(l_threads.get(i).m_stats);
            l_allStats.m_iterationDPS.add(l_threads.get(i).m_stats.m_totalDPS);
        }

        // Average out the stats for the number of iterations we ran
        l_allStats.divideBy(l_iterations);

        // Calculate standard deviation
        l_allStats.calculateTotalDPS();
        double l_overallTotalDPS = l_allStats.getTotalDPS();
        double l_runningTotal = 0.0;
        for (int i = 0; i < l_iterations; i++)
        {
            double l_difference = l_threads.get(i).m_stats.getTotalDPS() - l_overallTotalDPS;
            l_runningTotal += l_difference * l_difference;
        }
        
        l_allStats.m_standardDeviation = Math.sqrt(l_runningTotal / l_iterations);

        // TODO we need to return the random seeds here too so an iteration
        // can be recalculated to get the log (which should also be included
        return l_allStats;
    }
}
